package com.itheima.cs.common.dyewm;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.itheima.cs.R;
import com.itheima.cs.common.CustomCaptureActivity;
import com.itheima.cs.utils.BluetoothUtil;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class ScanResultActivity extends AppCompatActivity {
    private static final String TAG = "ScanResultActivity";

    private TextView tvCode, tvName, tvSpec;
    private List<ExtraInfo> extraInfos = new ArrayList<>();
    private ExtraInfoAdapter adapter;
    private String code,name,spec;


    private BluetoothSocket socket;
    private BluetoothAdapter btAdapter;

    private int extraScanPosition = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_result);


        tvCode = findViewById(R.id.tv_code);
        tvName = findViewById(R.id.tv_name);
        tvSpec = findViewById(R.id.tv_spec);
        ListView listView = findViewById(R.id.lv_extra_info);

        handleIntentData();

        btAdapter = BluetoothUtil.getBTAdapter();
        connectPrinter();
        Toolbar toolbar = findViewById(R.id.toolbar_dyewm);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        findViewById(R.id.btn_print).setOnClickListener(v -> printQRCode(generateQRContent()));
    }

    private void handleIntentData() {
        Intent intent = getIntent();
        if (intent != null) {
            code = intent.getStringExtra("code");
            name = intent.getStringExtra("name");
            spec = intent.getStringExtra("spec");

            tvCode.setText("编码：" + code);
            tvName.setText("名称：" + name);
            tvSpec.setText("规格：" + spec);
        }
    }


    private String generateQRContent() {
        StringBuilder sb = new StringBuilder();
        sb.append(code);

        for (ExtraInfo info : extraInfos) {
            if (!info.getValue().trim().isEmpty()) {
                sb.append(",").append(info.getType()).append(":").append(info.getValue());
            }
        }
        return sb.toString();
    }

    private void printQRCode(String data) {
        try {
            if (!checkConnection()) return;

            byte[] init = {0x1B, 0x40};
            byte[] alignLeft = {0x1B, 0x61, 0x00};
            byte[] qrModel = {0x1D, 0x28, 0x6B, 0x04, 0x00, 0x31, 0x41, 0x32, 0x00};
            byte[] qrSize = {0x1D, 0x28, 0x6B, 0x03, 0x00, 0x31, 0x43, 0x08};
            byte[] qrECLevel = {0x1D, 0x28, 0x6B, 0x03, 0x00, 0x31, 0x45, 0x31};
            byte[] dataBytes = data.getBytes("UTF-8");
            byte[] qrDataHeader = {
                    0x1D, 0x28, 0x6B,
                    (byte) (dataBytes.length + 3), 0x00,
                    0x31, 0x50, 0x30
            };
            byte[] qrPrint = {0x1D, 0x28, 0x6B, 0x03, 0x00, 0x31, 0x51, 0x30};
            byte[] feedAfter = {0x1B, 0x64, 0x05};

            byte[] bytes = concatBytes(
                    init,
                    alignLeft,
                    qrModel,
                    qrSize,
                    qrECLevel,
                    qrDataHeader,
                    dataBytes,
                    qrPrint,
                    feedAfter,
                    new byte[]{0x1D, 0x56, 0x42, 0x00}
            );

            BluetoothUtil.sendData(bytes, socket);
            showToast("二维码打印指令已发送");
        } catch (Exception e) {
            handleException(e);
        }
    }

    private class ExtraInfoAdapter extends BaseAdapter {
        private Context context;
        private List<ExtraInfo> data;

        public ExtraInfoAdapter(Context context, List<ExtraInfo> data) {
            this.context = context;
            this.data = data;
        }



        @Override public int getCount() { return data.size(); }
        @Override public Object getItem(int position) { return data.get(position); }
        @Override public long getItemId(int position) { return position; }

        class ViewHolder {
            Spinner spType;
            EditText etValue;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = new ViewHolder();
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.item_extra_info, parent, false);
                holder = new ViewHolder();
                holder.spType = convertView.findViewById(R.id.sp_type);
                holder.etValue = convertView.findViewById(R.id.et_value);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            ExtraInfo info = data.get(position);

            ArrayAdapter<String> typeAdapter = new ArrayAdapter<>(
                    context,
                    android.R.layout.simple_spinner_item,
                    new String[]{"工序", "仓库", "批次", "供应商"}
            );
            holder.spType.setAdapter(typeAdapter);
            holder.spType.setSelection(getPositionForType(info.getType()));
            holder.spType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                    info.setType((String) parent.getItemAtPosition(pos));
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {}
            });
            holder.etValue.setText(info.getValue());
            holder.etValue.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {}


                @Override
                public void afterTextChanged(Editable s) {
                    info.setValue(s.toString());
                }
            });

            holder.etValue.setOnClickListener(v -> {
                IntentIntegrator integrator = new IntentIntegrator(ScanResultActivity.this);
                integrator.setCaptureActivity(CustomCaptureActivity.class);
                integrator.initiateScan();
                extraScanPosition = position;
            });

            return convertView;
        }

        private int getPositionForType(String type) {
            switch (type) {
                case "仓库": return 1;
                case "批次": return 2;
                case "供应商": return 3;
                default: return 0;
            }
        }
    }

    private class ExtraInfo {
        private String type = "工序";
        private String value = "";

        public String getType() { return type; }
        public String getValue() { return value; }
        public void setType(String type) { this.type = type; }
        public void setValue(String value) { this.value = value; }
    }

    private void connectPrinter() {
        try {
            if (socket != null) {
                socket.close();
            }
            BluetoothDevice device = BluetoothUtil.getDevice(btAdapter);
            if (device == null) {
                showToast("未找到打印机");
                return;
            }
            socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
            socket.connect();
            showToast("打印机连接成功");
        } catch (IOException e) {
            showToast("连接失败: " + e.getMessage());
            socket = null;
        }
    }
    private boolean checkConnection() {
        if (socket == null || !socket.isConnected()) {
            connectPrinter();
            if (socket == null || !socket.isConnected()) {
                showToast("打印机未连接");
                return false;
            }
        }
        return true;
    }

    private void sendToPrinter(byte[] data) throws IOException {
        OutputStream os = socket.getOutputStream();
        os.write(data);
        os.flush();
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    private void handleException(Exception e) {
        showToast("打印失败: " + e.getMessage());
        try {
            if (socket != null) socket.close();
        } catch (IOException ex) {
        }
        socket = null;
    }

    private byte[] concatBytes(byte[]... arrays) {
        int length = 0;
        for (byte[] array : arrays) length += array.length;
        byte[] result = new byte[length];
        int pos = 0;
        for (byte[] array : arrays) {
            System.arraycopy(array, 0, result, pos, array.length);
            pos += array.length;
        }
        return result;
    }

    private void showToast(String msg) {
        runOnUiThread(() -> Toast.makeText(this, msg, Toast.LENGTH_SHORT).show());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if (socket != null) socket.close();
        } catch (IOException e) {
        }
    }
}
